//
//  YCLoginViewController.m
//  YCSchool
//
//  Created by gmall on 16/5/7.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  登录界面

#import "YCLoginViewController.h"
#import "YCHomeViewController.h"
#import "YCRegisterViewController.h"
#import "YCForgetPasswordViewController.h"
#import "YCNavigationViewController.h"
#import "YCHomeViewController.h"
#import "YCRegisterImproveViewController.h"

NSString * const LoginUserNameKey = @"LoginUserName";

@interface YCLoginViewController ()<UITextFieldDelegate>

/** scrollView  */
@property (nonatomic, strong) UIScrollView *scrollView;
/** contentView  */
@property (nonatomic, strong) UIView *contentView;

///登录标题
@property (nonatomic,readonly) UILabel *loginLabel;
///用户名
@property (nonatomic,readonly) UITextField *usernameField;
///用户密码
@property (nonatomic,readonly) UITextField *passwordField;
///登录按钮
@property (nonatomic,readonly) UIButton *loginButton;
///申请注册按钮
@property (nonatomic,readonly) UIButton *registerButton;
///忘记密码按钮
@property (nonatomic,readonly) UIButton *forgetPasswordButton;
///logo视图
@property (nonatomic,readonly) UIImageView *logoImageView;

/** 记录当前第一响应view转到window的frame  */
@property (nonatomic, assign) CGRect firstResponseViewFrameOfWindow;

/** 用户模型  */
@property (nonatomic, strong) YCLoginUser *userModel;

@end

@implementation YCLoginViewController

@synthesize loginLabel = _loginLabel;
@synthesize usernameField = _usernameField;
@synthesize passwordField = _passwordField;
@synthesize loginButton = _loginButton;
@synthesize registerButton = _registerButton;
@synthesize forgetPasswordButton = _forgetPasswordButton;
@synthesize logoImageView = _logoImageView;

#pragma mark - 懒加载
// 登录文字
- (UILabel *)loginLabel
{
    if(!_loginLabel)
    {
        _loginLabel = [[UILabel alloc] init];
        _loginLabel.text = @"登录";
        _loginLabel.textColor = [UIColor yc_colorWithUInt:0x3d3e40];
        _loginLabel.textAlignment = NSTextAlignmentCenter;
        _loginLabel.font = [UIFont systemFontOfSize:28];
    }
    return _loginLabel;
}

// 登录帐号
- (UITextField *)usernameField
{
    if(!_usernameField)
    {
        _usernameField = [[UITextField alloc] init];
        _usernameField.layer.borderWidth = 1;
        _usernameField.layer.borderColor = [UIColor yc_colorWithUInt:0xe0e0e0].CGColor;
        _usernameField.layer.cornerRadius= 5;
        _usernameField.font = [UIFont systemFontOfSize:15];
        _usernameField.backgroundColor = [UIColor whiteColor];
        _usernameField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _usernameField.placeholder = NSLocalizedString(@"请输入帐号", nil);//有默认颜色
        _usernameField.returnKeyType = UIReturnKeyNext;
        _usernameField.textColor = [UIColor yc_colorWithUInt:0x3d3e40];
        _usernameField.delegate = self;
        _usernameField.text = [[NSUserDefaults standardUserDefaults] objectForKey:LoginUserNameKey];
        
        //leftView
        UILabel *tipLabel = [[UILabel alloc] init];
        tipLabel.font = [UIFont boldSystemFontOfSize:15];
        tipLabel.frame = CGRectMake(0, 0, 54, 40);
        tipLabel.textColor = [UIColor yc_colorWithUInt:0x3d3e40];
        tipLabel.text = NSLocalizedString(@"帐号", nil);
        tipLabel.textAlignment = NSTextAlignmentCenter;
        _usernameField.leftView = tipLabel;
        _usernameField.leftViewMode = UITextFieldViewModeAlways;
    }
    return _usernameField;
}

- (UITextField *)passwordField
{
    if(!_passwordField)
    {
        _passwordField = [[UITextField alloc] init];
        _passwordField.layer.borderWidth = 1;
        _passwordField.layer.borderColor = [UIColor yc_colorWithUInt:0xc8c7cc].CGColor;
        _passwordField.layer.cornerRadius= 5;
        _passwordField.backgroundColor = [UIColor whiteColor];
        _passwordField.placeholder = NSLocalizedString(@"请输入密码", nil);
        _passwordField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _passwordField.font = [UIFont systemFontOfSize:15];
        _passwordField.textColor = [UIColor yc_colorWithUInt:0x3d3e40];
        _passwordField.secureTextEntry = YES;
        _passwordField.returnKeyType = UIReturnKeyDone;
        _passwordField.delegate = self;
        
        UILabel *tipLabel = [[UILabel alloc] init];
        tipLabel.font = [UIFont boldSystemFontOfSize:15];
        tipLabel.frame = CGRectMake(0, 0, 54, 40);
        tipLabel.textColor = [UIColor yc_colorWithUInt:0x3d3e40];
        tipLabel.text = NSLocalizedString(@"密码", nil);
        tipLabel.textAlignment = NSTextAlignmentCenter;
        _passwordField.leftView = tipLabel;
        _passwordField.leftViewMode = UITextFieldViewModeAlways;
    }
    return _passwordField;
}

- (UIButton *)forgetPasswordButton
{
    if(!_forgetPasswordButton)
    {
        _forgetPasswordButton = [[UIButton alloc] init];
        _forgetPasswordButton.titleLabel.font = [UIFont systemFontOfSize:12.0];
        [_forgetPasswordButton setTitleColor:[UIColor yc_colorWithUInt:0xb3b3b3] forState:UIControlStateNormal];
        [_forgetPasswordButton setTitle:NSLocalizedString(@"忘记密码？", nil) forState:UIControlStateNormal];
        _forgetPasswordButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_forgetPasswordButton addTarget:self action:@selector(didTouchUpInsideForgetPasswordButton:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _forgetPasswordButton;
}

- (UIButton *)loginButton
{
    if(!_loginButton)
    {
        _loginButton = [[UIButton alloc] init];
        _loginButton.titleLabel.font = [UIFont boldSystemFontOfSize:15];
        [_loginButton setTitleColor:[UIColor yc_colorWithUInt:0x3d3e40] forState:UIControlStateNormal];
        _loginButton.backgroundColor = [UIColor yc_colorWithUInt:0xf8bb36];
        _loginButton.layer.cornerRadius = 17.5;
        [_loginButton setTitle:NSLocalizedString(@"登录", nil) forState:UIControlStateNormal];
        [_loginButton addTarget:self action:@selector(didTouchUpInsideLoginButton:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _loginButton;
}

- (UIButton *)registerButton
{
    if(!_registerButton)
    {
        _registerButton = [[UIButton alloc] init];
        _registerButton.titleLabel.font = [UIFont systemFontOfSize:15];
        _registerButton.backgroundColor = [UIColor yc_colorWithUInt:0x3d3e40];
        _registerButton.layer.cornerRadius = 17.5;
        [_registerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_registerButton setTitle:NSLocalizedString(@"注册", nil) forState:UIControlStateNormal];
        [_registerButton addTarget:self action:@selector(didTouchUpInsideRegisterButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _registerButton;
}

- (UIImageView *)logoImageView
{
    if(!_logoImageView)
    {
        _logoImageView = [[UIImageView alloc] init];
        _logoImageView.image = [UIImage imageNamed:@"logo"];
        _logoImageView.layer.cornerRadius = 39 / 2.0;//39*39
        _logoImageView.layer.masksToBounds = YES;
    }
    return _logoImageView;
}

#pragma mark - 生命周期

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self makeView];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveKeyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    
    NSString *nickName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userNicknameKey"];
    YCLoginUser *lastLoginUserModel = [YCLoginUser loginUserWithName:nickName];
    self.usernameField.text = lastLoginUserModel.userNickname;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)makeView
{
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollView.alwaysBounceVertical = YES;
//    self.scrollView.backgroundColor = [UIColor yc_colorWithUInt:0xf7f7f7];
    self.scrollView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0);
    // 添加单击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapScrollView:)];
    [self.scrollView addGestureRecognizer:tap];
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    
    UIView *contentView = [[UIView alloc] init];
    contentView.backgroundColor = [UIColor yc_colorWithUInt:0xf7f7f7];
    self.contentView = contentView;
    [self.scrollView addSubview:contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    [self.contentView addSubview:self.loginLabel];
    [self.contentView addSubview:self.usernameField];
    [self.contentView addSubview:self.passwordField];
    [self.contentView addSubview:self.loginButton];
    [self.contentView addSubview:self.forgetPasswordButton];
    [self.contentView addSubview:self.registerButton];
    [self.contentView addSubview:self.logoImageView];
    
    [_loginLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        [YCAdapter performOtherBlock:^{
            make.top.equalTo(self.contentView).offset(60);
        } IPhone6Block:^{
            make.top.equalTo(self.contentView).offset(140);
        } IPhone6pBlock:^{
            make.top.equalTo(self.contentView).offset(150);
        }];
        
        make.centerX.equalTo(self.contentView);
    }];
    
    [_usernameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_loginLabel.mas_bottom).with.offset(heightFromIphone6Height(78));
        make.centerX.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(47);
        make.right.equalTo(self.contentView).offset(-47);
        make.height.equalTo(@40);
    }];
    
    [_passwordField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_usernameField.mas_bottom).with.offset(heightFromIphone6Height(14));
        make.centerX.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(47);
        make.right.equalTo(self.contentView).offset(-47);
        make.height.equalTo(@40);
    }];
    
    [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_passwordField.mas_bottom).with.offset(heightFromIphone6Height(25));
        make.centerX.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(47);
        make.right.equalTo(self.contentView).offset(-47);
        make.height.equalTo(@36);
    }];
    
    // 里面内容设置了中心右对齐
    [_forgetPasswordButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_loginButton.mas_bottom).offset(heightFromIphone6Height(14));
        make.centerX.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(47);
        make.right.equalTo(self.contentView).offset(-47);
        make.height.equalTo(@12);
    }];
    
    [_registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_forgetPasswordButton.mas_bottom).with.offset(heightFromIphone6Height(15));
        make.centerX.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(47);
        make.right.equalTo(self.contentView).offset(-47);
        make.height.equalTo(@36);
    }];
    
    [_logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        [YCAdapter performOtherBlock:^{
            make.top.equalTo(self.registerButton.mas_bottom).with.offset(45);
        } IPhone6Block:^{
            make.top.equalTo(self.registerButton.mas_bottom).with.offset(89);
        } IPhone6pBlock:^{
            make.top.equalTo(self.contentView).offset(100);
        }];
        
        make.centerX.equalTo(self.contentView);
        make.width.height.equalTo(@39);// 39*39
    }];
    [self.contentView layoutIfNeeded];
    CGFloat contentH = CGRectGetMaxY(_logoImageView.frame);
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.equalTo(_logoImageView.mas_bottom).offset(heightFromIphone6Height(63));
        make.bottom.equalTo(_logoImageView.mas_bottom).offset(kScreenHeight - contentH);
    }];
    
    [self.view layoutIfNeeded];
    self.scrollView.contentSize = CGSizeMake(0, CGRectGetMaxY(self.contentView.frame)-20);
}

                                
#pragma mark -- 响应事件
                                
///登录按钮
- (void)didTouchUpInsideLoginButton:(UIButton *)button
{
    [self.view endEditing:YES];
    
    self.userModel = [YCLoginUser loginUserWithName:[self.usernameField.text yc_trimString]];
    if (!self.userModel) {
        [YCAlertView showMsg:@"该帐号还未注册"];//由于还不知道登录接口要不要token,uid,因此先这样.只限制在本机注册的登录.
        return;
    }
    
    if (self.usernameField.text.length < 1)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入帐号"];
        return;
    }

    if (self.passwordField.text.length < 1)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入密码"];
        return;
    }
    
//    if (self.userModel.userToken == nil) {
//        [YCAlertView showMsg:@"该帐号还未注册"];
//        return;
//    }

    NSString *nameStr = [_usernameField.text yc_trimString];
    NSString *passwordStr = [[_passwordField.text yc_trimString] yc_md5String];
    
    NSDictionary *params = @{
                             @"mobile":@"15000000000",//nameStr,
                             @"password":@"e10adc3949ba59abbe56e057f20f883e"//passwordStr
                             };

    [SVProgressHUD showWithStatus:@"登录中..."];
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [SVProgressHUD dismiss];
//        
//        //保存当前用户名
//        [[NSUserDefaults standardUserDefaults] setObject:nameStr forKey:@"userNicknameKey"];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//        
//        UIViewController *rootVc = [[YCHomeViewController alloc] init];
//        YCNavigationViewController *nav = [[YCNavigationViewController alloc] initWithRootViewController:rootVc];
//        [UIApplication sharedApplication].keyWindow.rootViewController = nav;
//    });
    
    [[YCNetworManager shareManager] postWithUrl:YCAPILogin params:params success:^(NSURLSessionDataTask *task, ServiceResponse *response) {
        YCLog(@"响应消息--%@,响应内容:%@--",response.message,response.data);
        [SVProgressHUD dismiss];
        // 登录成功后,会返回uid与token
        NSDictionary *dict = response.data;
        self.userModel.userId = ((NSString *)dict[@"uid"]).intValue;
        self.userModel.userToken = dict[@"token"];
        [YCLoginUser loginWithUser:self.userModel];//更新下token与uid等参数
        
        // 如果返回状态为100,则跳到完善资料页
        if (response.code == ServiceResponseCodeImproveInfo) {
            YCRegisterImproveViewController *improveVc = [[YCRegisterImproveViewController alloc] initWithUserModel:self.userModel];
            [self.navigationController pushViewController:improveVc animated:YES];
            return ;
        }
        
        UIViewController *rootVc = [[YCHomeViewController alloc] init];
        YCNavigationViewController *nav = [[YCNavigationViewController alloc] initWithRootViewController:rootVc];
        [UIApplication sharedApplication].keyWindow.rootViewController = nav;
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        YCLog(@"%@",error.localizedDescription);
        [SVProgressHUD dismiss];
    }];
    
    
}
                            
///忘记密码按钮
- (void)didTouchUpInsideForgetPasswordButton:(UIButton *)button
{
    YCLogFunc
    YCForgetPasswordViewController *vc = [[YCForgetPasswordViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
                            
///注册按钮
- (void)didTouchUpInsideRegisterButton:(UIButton *)button
{
    YCLogFunc
    YCRegisterViewController *vc = [[YCRegisterViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
                            
///点击回弹键盘
- (void)tapScrollView:(UITapGestureRecognizer *)tap
{
    YCLogFunc
    [self.view endEditing:YES];
}
                                
#pragma mark - UITextField delegate
                                
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return YES;
}
                            
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if(textField == self.usernameField)
    {
        [self.passwordField becomeFirstResponder];
    }
    else
    {
        [self.loginButton sendActionsForControlEvents:UIControlEventTouchUpInside];
    }
    return YES;
}

 
#pragma mark - 通知回调
                                
///键盘将要弹出通知回调
- (void)receiveKeyboardWillChangeFrameNotification:(NSNotification *)notification
{
    CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 获取当前第一响应view
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIView *firstResponseView = [keyWindow performSelector:@selector(firstResponder)];
   
    _firstResponseViewFrameOfWindow = [self.view convertRect:firstResponseView.frame toView:keyWindow];
    if(rect.origin.y < kScreenHeight)//键盘上弹了
    {
        CGFloat offset = CGRectGetMaxY(_firstResponseViewFrameOfWindow) - CGRectGetMinY(rect)+15;//高出15
        if(offset < 0 ) return;
        rect = self.view.bounds;
        rect.origin.y = (offset);
        [UIView animateWithDuration:duration animations:^{
            self.view.bounds = rect;
        }];
    }
    else
    {
        [UIView animateWithDuration:duration animations:^{
            self.view.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
        }];
    }
}

@end
